//
//  ClubJoinedMoreStrategyVC.swift
//  77Club
//
//  Created by Apple on 2024/9/5.
//

import UIKit

class ClubJoinedMoreStrategyVC: ClubBaseViewController {

    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubStrategyListView.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 80.0.Scale
        return tableView
    }()
    private let topView = c_make_ex(UIView.self)
        .bgColor("#F7F8FA".toColor.alpha(0.8)).end()
    private let lineView = c_make_ex(UIView.self)
        .bgColor("#E4E5E6").end()
    private let backButton = UIIconButton(style: .leading(itemSpace: 0))
    var models:[ClubGameCommunityAllListModel] = []
    private var pageIndex = 1
    
    var joinedStrategy: ((_ md: ClubGameCommunityAllListModel) -> Void)?
    
    var is_bbs = "0" {
        didSet{
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                if self.is_bbs == "1" {
                    self.backButton.setTitle("其他论坛", for: .normal)
                }else{
                    self.backButton.setTitle("加入更多的论坛", for: .normal)
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            topView
            lineView
            backButton
            tableView
        }
        
        backButton.style { v in
            v.iconSize = CGSize(width: 56.0.Scale, height: 44.0.Scale)
            v.setImage("Common_blackBack".toImage, for: .normal)
            v.setTitle("加入更多的论坛", for: .normal)
            v.setTitleColor(.black, for: .normal)
            v.titleLabel?.font = 16.font_semiBold
            v.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
            v.contentHorizontalAlignment = .leading
        }
        
        topView.leading(0).trailing(0).height(.navi_height).top(0)
        lineView.leading(0).trailing(0).height(1).top(.navi_height)
        backButton.leading(0).top(.statusHeight).height(44.0.Scale)
        tableView.leading(0).trailing(0).bottom(0).top(.navi_height + 1)
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubJoinedMoreStrategyVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return models.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubStrategyListView", for: indexPath) as! ClubStrategyListView
        cell.model = models[indexPath.row]
        cell.joinStrategy = { md in
            self.joinedStrategy?(md)
            if let index = self.models.firstIndex(where: { $0.id == md.id }) {
                self.models.remove(at: index)
            }
            tableView.reloadData()
        }
        cell.todDetailVC = { md in
            if md.is_bbs == 1 {
                let community = ClubSquareDatailViewController()
                community.communityId = md.id
                self.navigationController?.pushViewController(community, animated: true)
            }else{
                let community = ClubGameDetailViewController()
                community.gameId = md.id
                community.toForum = true
                self.navigationController?.pushViewController(community, animated: true)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if self.is_bbs == "1" {
            let md = models[indexPath.row]
            let community = ClubSquareDatailViewController()
            community.communityId = md.id
            self.navigationController?.pushViewController(community, animated: true)
            if var localData: [ClubGameCommunityAllListModel] = UserDefaultsManager.getModelsData(forKey: .browseHistory) {
                if !localData.contains(where: { $0.id == md.id }) {
                    localData.append(md)
                    UserDefaultsManager.setModelsData(localData, forKey: .browseHistory)
                }
            }else{
                UserDefaultsManager.setModelsData([md], forKey: .browseHistory)
            }
        }else{
            
            let community = ClubGameDetailViewController()
            community.gameId = models[indexPath.row].id
            community.toForum = true
            self.navigationController?.pushViewController(community, animated: true)
        }
    }

}

//MARK: data
extension ClubJoinedMoreStrategyVC {
    
    func loadData() -> Void {

        ToastUtil.show()
        Task {
            var user_id = ""
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                user_id = uid
            }
            let type = (self.is_bbs == "1") ? "" : "3"
            let res = await self.network.requestMoreData(.communityList(page: pageIndex, type: type, keyword: "", uid: user_id, is_bbs: self.is_bbs),type: ClubGameSquareListModel.self)
            ToastUtil.dismiss()
            tableView.refresh_end()
            if res.isSuccess, let models = res.model?.data {
                self.models.removeAll()
                self.models = models
                self.tableView.reloadData()
            }
        }
    }
    
    
    @objc func loadNewData() -> () {
        pageIndex = 1
        loadData()
    }
    
    @objc func loadMoreData() -> () {

        pageIndex += 1
        Task {
            var user_id = ""
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                user_id = uid
            }
            let type = (self.is_bbs == "1") ? "" : "3"
            let res = await self.network.requestMoreData(.communityList(page: pageIndex, type: type, keyword: "", uid: user_id, is_bbs: self.is_bbs),type: ClubGameSquareListModel.self)
            tableView.refresh_end()
            if res.isSuccess, let models = res.model?.data {
                self.models.append(contentsOf: models)
                self.tableView.reloadData()
            }
        }
    }
}
